package com.samnative.pineapple.main;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.samnative.pineapple.http.HttpRequest;
import com.samnative.pineapple.http.JsonResult;
import com.samnative.pineapple.instance.AppPrefer;
import com.samnative.pineapple.value.Config;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * 全部搜索结果,可能包含医院,细胞存储单位等
 * 接口可能不同
 */
public class AllSearchResultActivity extends BaseActivity implements View.OnClickListener {


    private SmartRefreshLayout swipeRefreshLayout;

    /**
     * 标题栏背景,根据滑动来变色
     */
    private View v_top;
    /**
     * 状态栏底色
     */
    private View bar_top;
    /**
     * 图标
     */
    private ImageView iv_icon, iv_voice, iv_back;
    /**
     * 搜索框
     */
    private EditText et_search;
    /**
     * 页数
     */
    private int page = 1;
    /**
     * 搜索关键字
     */
    private String keyword;
    /**
     * 无数据时显示
     */
    private TextView tv_no_data;
    /**
     * 布局容器
     */
    private LinearLayout ll_content;
    /**
     * 1为细胞存储单位 2为医院 3为存储单位+医院 4为存储单位+医院+产品
     */
    private int type;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_all_search_result;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        type = getIntent().getIntExtra("type", 4);
        keyword = getIntent().getStringExtra("keyword");
        iv_back = find(R.id.iv_back);
        iv_back.setOnClickListener(this);

        ll_content = find(R.id.ll_content);
        tv_no_data = find(R.id.tv_no_data);
        v_top = find(R.id.v_top);
        bar_top = find(R.id.bar_top);
        iv_icon = find(R.id.iv_icon);
        iv_voice = find(R.id.iv_voice);
        iv_voice.setOnClickListener(this);
        et_search = find(R.id.et_search);
        et_search.setText(keyword);
        et_search.setSelection(keyword.length());

        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (et_search.getText().toString().isEmpty()) {
                        return true;
                    }
                    page = 1;
                    requestData();
                    return true;
                }
                return false;
            }
        });


        swipeRefreshLayout = find(R.id.swipeRefreshLayout);


//        swipeRefreshLayout.autoRefresh();//自动刷新
        swipeRefreshLayout.autoLoadMore();//自动加载
        swipeRefreshLayout.setEnableLoadMore(false);
        swipeRefreshLayout.setFooterHeight(32);
        swipeRefreshLayout.setEnableFooterTranslationContent(false);
        swipeRefreshLayout.setRefreshHeader(new MaterialHeader(mContext).setShowBezierWave(false));//显示Material系统风格的head
        swipeRefreshLayout.setRefreshFooter(new ClassicsFooter(mContext).setFinishDuration(0).setTextSizeTitle(12));//经典foot ,不显示时间


        swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                requestData();
            }
        });

//        swipeRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
//            @Override
//            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//                requestData();
//            }
//        });

        requestData();
    }


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    }


    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

//        String newCity = AppPrefer.getInstance(mContext).getString(AppPrefer.currentCity, "");
//        if (!newCity.isEmpty() && !tv_city.getText().toString().equals(newCity)) {
//            tv_city.setText(newCity);
//            FancyToast.showToast(mContext, "城市切换了", FancyToast.DEFAULT, true);
//        }

    }


    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_voice:
                break;
            default:
                break;
        }

    }

    /**
     * 取细胞储存搜索列表.不传库ID
     */
    public void requestData() {
        Map<String, String> map = new HashMap<>();
        map.put("_apiname", "appoint.index.appointlist");
        map.put("type", String.valueOf(type));
        map.put("city_id", AppPrefer.getInstance(mContext).getString(AppPrefer.currentCityCode, ""));
        map.put("keywords", et_search.getText().toString());
        map.put("page", String.valueOf(page));
        map.put("lngx", Config.longitude);
        map.put("laty", Config.latitude);
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                try {
                    JSONObject data = result.getJSONObject("data");

                    //这一级的list为搜索出来的种类
                    JSONArray list = data.getJSONArray("list");

                    ll_content.removeAllViews();

//                    for (int i = 0; i < list.length(); i++) {
//
//                        //解析每种类下面的列表
//                        JSONObject jobj = list.getJSONObject(i);
//                        String name = jobj.optString("name");
//                        String title = jobj.optString("title");
//                        JSONArray listsub = jobj.getJSONArray("list");
//                        ll_content.addView(addResultTypeList(title, name, listsub.toString()));
//                    }


                    if (list.length() > 0) {
                        tv_no_data.setVisibility(View.GONE);
                    } else {
                        tv_no_data.setVisibility(View.VISIBLE);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void requestFailure(int code, String msg) {
                super.requestFailure(code, msg);
                swipeRefreshLayout.finishLoadMore();
            }

            @Override
            public void requestFinish() {
                super.requestFinish();
                swipeRefreshLayout.finishRefresh();
            }
        });
    }




    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    //=============================================================================


}
